<template>
  <div>
    <el-button size="mini" type="primary" @click="showDialog">图片文件/excel图片</el-button>

    <el-dialog
      title="批量上传图片"
      :visible.sync="dialogVisible"
      append-to-body
      width="70%"
      :before-close="handleClose"
    >

      <el-form :model="form" label-width="160px">
        <el-form-item label="备注图片来源">
          <el-input
            v-model="form.note"
            placeholder="请输入统一备注，供应商或者收集链接等，后续能够查找该产品出处"
          />
        </el-form-item>
        <el-form-item label="加水印">
          <el-switch
            v-model="form.addwatermark"
            active-text="加水印"
            inactive-text="不加"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
          <el-switch
            v-model="form.removebg"
            active-text="去背景"
            inactive-text="不去"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
      </el-form>

      <div v-if="form.note.length" class="upload-container">
        <el-upload
          ref="upload"
          :headers="headers"
          :action="uploadUrl"
          :multiple="true"
          drag
          :auto-upload="false"
          :file-list="fileList"
          :show-file-list="true"
          :before-upload="beforeUpload"
          :data="uploadData"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div slot="tip" class="el-upload__tip">支持jpg、png等图片格式或者excel文件</div>
        </el-upload>

        <div class="upload-actions">
          <el-button
            style="margin-top: 10px"
            size="small"
            type="primary"
            @click="submitUpload"
          >
            开始上传
          </el-button>
        </div>

        <!-- 上传成功的预览区域 -->
        <div v-if="successList.length > 0" class="upload-preview">
          <h4>上传成功：</h4>
          <div class="preview-list">
            <div
              v-for="(item, index) in successList"
              :key="index"
              class="preview-item"
            >
              <el-image
                :src="item.url"
                :preview-src-list="[item.url]"
                class="preview-image"
              />
              <div class="preview-url">{{ item.url }}</div>
            </div>
          </div>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" :disabled="!successList.length" @click="handleConfirm">插入选中图片</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'

export default {
  name: 'ImageUploadDialog',
  props: {
    // 上传地址
    action: {
      type: String,
      required: true
    },
    // 上传时附带的额外参数
    data: {
      type: Object,
      default: () => ({})
    }
  },

  data() {
    return {
      dialogVisible: false,
      form: {
        note: '',
        addwatermark: true,
        removebg: true
      },
      uploadUrl: this.action,
      fileList: [],
      successList: [], // 上传成功的文件列表
      listObj: {},
      uploadData: {
        ...this.data
      }
    }
  },

  computed: {
    headers() {
      return {
        'Authorization': getToken(),
        'PTOKEN': this.$store.getters.projectId
      }
    }
  },

  methods: {
    showDialog() {
      this.dialogVisible = true
    },

    handleClose() {
      this.$confirm('关闭后已上传的图片信息将丢失, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dialogVisible = false
        this.clearFiles()
        this.form.note = ''
      }).catch(() => {})
    },

    handleConfirm() {
      // 为每个成功上传的图片创建一个新的产品对象
      const newProducts = this.successList.map(item => ({
        sku: Math.random().toString(36).substr(2, 8),
        images: [item.url],
        price: 0,
        activeName: 'first',
        currency: 'USD',
        note: this.form.note, // 使用统一备注
        moq: 100,
        parameters: '',
        parameters_en: ''
      }))

      // 触发事件，将新产品添加到父组件的selected列表
      this.$emit('on-batch-insert', newProducts)

      // 关闭对话框并清理状态
      this.dialogVisible = false
      this.clearFiles()
      this.form.note = ''

      // 提示用户
      this.$message.success(`成功添加 ${newProducts.length} 个产品`)
    },

    beforeUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                      file.type === 'application/vnd.ms-excel' ||
                      file.name.endsWith('.xlsx') ||
                      file.name.endsWith('.xls')
      if (isExcel) {
        this.uploadData.task = 'extract_images'
      } else {
        this.uploadData.task = ''
      }
      this.uploadData.addwatermark = this.form.addwatermark
      this.uploadData.removebg = this.form.removebg
      if (!isExcel && !isImage) {
        this.$message.error('只能上传Excel文件！')
        return false
      }
      const isLt10M = file.size / 1024 / 1024 < 100
      if (!isLt10M) {
        this.$message.error('图片大小不能超过 100MB！')
        return false
      }

      const fileName = file.uid
      this.listObj[fileName] = {
        hasSuccess: false,
        uid: file.uid,
        name: file.name
      }

      return true
    },

    submitUpload() {
      this.$refs.upload.submit()
    },

    handleRemove(file) {
      const uid = file.uid
      const objKeyArr = Object.keys(this.listObj)
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          delete this.listObj[objKeyArr[i]]
          break
        }
      }
      this.successList = this.successList.filter(item => item.uid !== uid)
    },

    handleSuccess(response, file) {
      if (response.success) {
        const uid = file.uid
        if (response.images) {
          this.$message.success('图片提取成功')
          for (let i = 0, len = response.images.length; i < len; i++) {
            const item = response.images[i]
            this.successList.push({
              uid: i, // 随机生成一个uid
              name: item.name,
              url: item.url
            })
          }
          console.log(this.successList)
          return
        }
        if (this.listObj[uid]) {
          this.listObj[uid].hasSuccess = true
          this.listObj[uid].url = response.data.url
        }

        this.successList.push({
          uid: file.uid,
          name: file.name,
          url: response.data.url
        })

        this.$message.success(`${file.name} 上传成功`)
      } else {
        this.$message.error(`${file.name} 上传失败: ${response.msg}`)
      }
    },

    clearFiles() {
      this.fileList = []
      this.successList = []
      this.listObj = {}
      this.$refs.upload && this.$refs.upload.clearFiles()
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-container {
  padding: 20px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;

  .upload-actions {
    margin: 10px 0;
  }

  .upload-preview {
    margin-top: 20px;

    h4 {
      margin-bottom: 10px;
      color: #606266;
    }

    .preview-list {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;

      .preview-item {
        width: 200px;

        .preview-image {
          width: 100%;
          height: 150px;
          object-fit: cover;
          border-radius: 4px;
        }

        .preview-url {
          margin-top: 5px;
          font-size: 12px;
          color: #909399;
          word-break: break-all;
        }
      }
    }
  }
}
</style>
